layui.use(['form', 'layer', 'layedit', 'laydate', 'table', 'upload'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        layedit = layui.layedit,
        upload = layui.upload,
        table = layui.table,
        laypage = layui.laypage;
         laydate = layui.laydate;
    layedit.sync(editIndex);

    laydate.render({
        elem: '#opentime',
        type: 'datetime'
    });

    form.render();
    var tableIns = table.render({});
    var limitcount = 10;
    var curnum = 1;
    var method_name = 'SpotView';
    initData();


    function initData(name) {
        $.ajax({
            url: public_url + 'public/?service=SpotType.GetList',
            type: "get",
            success: function (data) {
                $.each(data.data.items, function (index, item) {
                    $('#zcySelect').append("<option value=" + item.id + ">" + item.name + "</option>");//往下拉菜单里添加元素
                });
                form.render();//菜单渲染 把内容加载进去
            }
        });
        if (name) {
            url = public_url + 'public/?service=' + method_name + '.GetList'
        } else {
            url = public_url + 'public/?service=' + method_name + '.GetList'
        }
        $.ajax({
            url: url,
            type: "post",
            data: {page: curnum, perpage: limitcount, word: name},
            success: function (data) {
                var total_size = data.data.total;
                tableIns = table.render({
                    elem: '#linkList',
                    page: false,
                    limit: 10,
                    id: "linkListTab",
                    count: total_size,
                    cols: [[
                        {type: "checkbox", fixed: "left", width: 50},
                        {field: 'id', title: 'ID', width: 80, align: "center"},
                        {field: 'title', title: '名称', width: 150, align: "center"},
                        {title: '预览图', width: 100, height: 100, templet: '#img', align: "center"},
                        {field: 'opentime', title: '开放时间', width: 200, align: "center"},
                        {field: 'customtel', title: '客服电话', width: 120, align: "center"},
                        {field: 'score', title: '评分', width: 80, align: "center"},
                        {field: 'address', title: '地址', width: 100, align: "center"},
                        {field: 'name', title: '分类', width: 100, align: "center"},
                        {field: 'price_start', title: '起始价格', width: 100, align: "center"},
                        {field: 'tag', title: '标签多个用,分隔', width: 100, align: "center"},
                        {field: 'brief_desc', title: '简介', align: "center"},
                        {title: '操作', width: 120, templet: '#orderListBar', fixed: "right", align: "center"}
                    ]],
                    data: data.data.items,
                    done: function (res, curr, count) {
                        laypage.render({
                            elem: 'fenye'
                            , count: total_size
                            , curr: curnum
                            , limit: limitcount
                            , layout: ['prev', 'page', 'next', 'skip', 'count']
                            , jump: function (obj, first) {
                                if (!first) {
                                    curnum = obj.curr;
                                    limitcount = obj.limit;
                                    initData()
                                }
                            }
                        })

                    }
                });
            },
            error: function (data) {
                var a = '';
            }
        })
    }

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        var search = $(".searchVal").val();
        limitcount = 10;
        curnum = 1;
        initData(search)
    });

    function addLink(edit) {
        var title = "添加景点";
        if (edit) {
            title = "修改景点";
        }
        urls = public_url + 'public/?service=SpotType.GetList';

        // $.ajax({
        //     url: urls,
        //     type: "post",
        //     data: {page: 1, perpage: 20},
        //     success: function (data) {
        //         $.each(data.data.items,function(index,item){
        //             $('#selectID').append(new Option(item.name,item.id));//往下拉菜单里添加元素
        //         })
        //         form.render();//菜单渲染 把内容加载进去
        //     },error:function (data) {
        //         var s=''
        //     }
        // })
        //$('#selectID').append(new Option('123','345'));//往下拉菜单里添加元素
        var index = layui.layer.open({
            title: title,
            type: 2,

            content: "spotViewAdd.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                // var body = $($(".layui-layer-iframe", parent.document).find("iframe")[0].contentWindow.document.body);
                if (edit) {
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    iframeWin.create_edi(edit.details)
                    body.find(".id").val(edit.id);
                    body.find(".title").val(edit.title);
                    // body.find(".small_img").attr("src",edit.small_img);

                    body.find('#img_demo').attr("src", edit.small_img);


                    body.find(".sort").val(edit.sort);
                    $("#zcySelect").select(edit.spot_type);
                    body.find(".tag").val(edit.tag);
                    body.find(".score").val(edit.score);
                    body.find(".price_start").val(edit.price_start);
                    body.find(".spot_type").val(edit.spot_type);
                    body.find(".brief_desc").val(edit.brief_desc);
                    body.find(".updatetime").val(edit.updatetime);
                    body.find(".customtel").val(edit.customtel);

                    body.find(".details").val(edit.details);

                    body.find(".address").val(edit.address);
                    body.find(".images").val(edit.images);
                    body.find(".opentime").val(edit.opentime);
                    body.find(".status_id").val(edit.status_id);
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回景点列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            },
            end: function () {
                location.reload();
            }
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        })
    }

    $(".add_btn").click(function () {
        addLink();
    });

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('linkListTab'),
            data = checkStatus.data;
        if (data.length > 0) {
            layer.confirm('确定删除选中的景点吗？', {icon: 3, title: '提示信息'}, function (index) {
                var size = data.length;
                for (var i in data) {
                    $.ajax({
                        url: public_url + 'public/?service=App.' + method_name + '.Delete',
                        type: "post",
                        data: {id: data[i].id},
                        success: function (data) {
                            if (i == size - 1) {
                                tableIns.reload();
                                initData();
                                layer.close(index);
                                layer.msg(data.data.msg)
                            }
                        }
                    })
                }

            })
        } else {
            layer.msg("请选择需要删除的景点");
        }
    });

    //每列的编辑和删除
    table.on('tool(linkList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        if (layEvent === 'edit') { //编辑
            addLink(data);
        } else if (layEvent === 'del') { //删除
            layer.confirm('确定删除此景点吗？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: public_url + 'public/?service=App.' + method_name + '.Delete',
                    type: "post",
                    data: {id: data.id},
                    success: function (datas) {
                        tableIns.reload();
                        initData();
                        layer.close(index);
                        layer.msg(datas.data.msg);
                    }
                })
            });
        }
    });

    form.on("submit(addLink)", function (data) {


        var index = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});
        if ($(".id").val()) {
            method = public_url + 'public/?service=App.' + method_name + '.Update';
        } else {
            method = public_url + 'public/?service=App.' + method_name + '.Insert';
        }
        var detail = layedit.getContent(editIndex)
        $.ajax({
            url: method,
            type: "post",
            data: {
                id: $(".id").val(),
                title: $(".title").val(),
                small_img: $("#img_url1").val(),
                small_img: $(".small_img")[0].src,
                sort: $(".sort").val(),
                tag: $(".tag").val(),
                score: $(".score").val(),
                price_start: $(".price_start").val(),
                spot_type: $(":selected", "#zcySelect").attr("value"),
                brief_desc: $(".brief_desc").val(),
                customtel: $(".customtel").val(),

                details: editor.txt.text(),

                address: $(".address").val(),
                images: $(".images").val(),
                opentime: $(".opentime").val(),
                status_id: $(".status_id").val()

            },
            success: function (data) {
                console.log(data);
                // top.layer.close(index);
                // layer.closeAll("iframe");
                top.layer.msg("更新成功");
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index);
            }, error: function (data) {
                var s = ""
            }
        });
        return false;
    })


    //创建一个编辑器
    var editIndex = layedit.build('news_content', {
        height: 505,
        uploadImage: {
            url: public_url + 'public/?service=App.' + 'Examples_Upload' + '.Go',
        }
    });
    //上传缩略图
//    upload.render({
//        elem: '.thumbBox',
//        url: '../../json/userface.json',
//        method : "get",  //此处是为了演示之用，实际使用中请将此删除，默认用post方式提交
//        done: function(res, index, upload){
//            var num = parseInt(4*Math.random());  //生成0-4的随机数，随机显示一个头像信息
//            $('.thumbImg').attr('src',res.data[num].src);
//            $('.thumbBox').css("background","#fff");
//        }
//    });

    var uploadInst = upload.render({
        elem: '#test1',
        url: public_url + 'public/?service=App.' + 'Examples_Upload' + '.Go',
        acceptMime: 'image/*',
        multiple: true,
        before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#img_demo').attr('src', result); //图片链接（base64）
            });
        },
        done: function (res) {
            //如果上传失败
            if (res.data.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
            console.log(res);
            picture = res.data.url;
            $("#img_url1").attr("value", picture)
        },
        error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText1');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });


});
